package com.zlcdgroup.android.leaflet

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.webkit.WebViewClient

/**
 *
 * @author: aking <a href="mailto:akingyin@163.com">Contact me.</a>
 * @since: 2025/7/14 10:03
 * @version: 1.0
 */
@SuppressLint("SetJavaScriptEnabled")
class MapView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : WebView(context, attrs) {

    private var mapListener:MapListener? = null

    private var hasInit = false

    fun setMapListener(mapListener: MapListener){
        this.mapListener = mapListener
    }

    init {
        val webSettings = settings
        webSettings.defaultTextEncodingName = "utf-8"
        //隐藏缩放按钮
        webSettings.builtInZoomControls = true
        //可任意比例绽放
        webSettings.useWideViewPort = true
        // setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式
        webSettings.loadWithOverviewMode = true
        webSettings.javaScriptEnabled = true
        addJavascriptInterface(JsInteration(), "Android")
        webSettings.domStorageEnabled = true
        webSettings.setSupportMultipleWindows(true)
        webSettings.useWideViewPort = true
        webSettings.allowFileAccess = true
        webSettings.setSupportZoom(true)
        isDrawingCacheEnabled = true
        buildDrawingCache()
        buildLayer()
        setLayerType(LAYER_TYPE_HARDWARE, null)
        webViewClient = MWebView()
        loadUrl("file:///android_asset/index.html")

    }



    fun setMapCenter(lat: Double, lng: Double) {
        if (hasInit){
            evaluateJavascript("javascript:setCenter(${lat}, ${lng})", null)
        }
    }

    fun addMarker(lat: Double, lng: Double,icon:String? = null,zIndexOffset:Int =0,title:String? = null) {
        if (hasInit){
            evaluateJavascript("javascript:addIconMarker(${lat}, ${lng},'${icon}')", null)
        }
    }

    private fun loadMethod(method: String) {
        if (hasInit) {
            evaluateJavascript("javascript:$method",null)
        }
    }
    inner class MWebView : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            hasInit = true
            mapListener?.onMapLoaded()
            println("加载完成")
        }
    }

    inner class JsInteration {

        @JavascriptInterface
        fun onMapMarkerClick(lat: Double, lng: Double,title: String?) {
            mapListener?.onMapMarkerClick(lat, lng,title)
        }
    }
}